<template>
    <div class="add-meeting">
        <!-- 头部导航 -->
        <header class="header">
          
                <div class="back-btn" @click="handleBack">
                    <el-icon>
                        <ArrowLeft />
                    </el-icon>
                    <span>返回</span>
                </div>
                <h1>发起会议</h1>
                <Time />
           
        </header>

        <div class="main-container" style="margin-top: -70px;">
            <div class="form-container">
                <!-- 会议题目 -->
                <div class="form-item">
                    <label>会议题目</label>
                    <input v-model="meetingForm.title" placeholder="请输入会议题目" />
                </div>

                <!-- 会议简介 -->
                <div class="form-item">
                    <label>会议简介</label>
                    <textarea v-model="meetingForm.description" rows="4" placeholder="请输入会议简介" style="font-family: '微软雅黑';width: 97.5%;"></textarea>
                    <div class="word-count">{{ meetingForm.description.length }}/200</div>
                </div>

                <!-- 主办方和会议签到时间在同一行 -->
                <div class="form-row">
                    <div class="form-item">
                        <label>主办方</label>
                        <input v-model="meetingForm.organizer" placeholder="请输入主办方" />
                    </div>

                    <div class="form-item date-picker-group">
                        <label>会议签到时间</label>
                        <div class="date-range-wrapper">
                                <el-date-picker 
                                    v-model="dateRange[0]" 
                                    type="datetime" 
                                    placeholder="开始日期时间" 
                                    class="date-picker"
                                    format="YYYY-MM-DD HH:mm"
                                    value-format="YYYY-MM-DD HH:mm"
                                />
                                <span class="separator">至</span>
                                <el-date-picker 
                                    v-model="dateRange[1]" 
                                    type="datetime" 
                                    placeholder="结束日期时间" 
                                    class="date-picker"
                                    format="YYYY-MM-DD HH:mm"
                                    value-format="YYYY-MM-DD HH:mm"
                                />
                            </div>
                    </div>
                </div>

                <!-- 会议地点、具体地点和上传按钮在同一行 -->
                <div class="location-row">
                    <div class="form-item">
                        <label>会议地点(签到地点)</label>
                        <div class="location-input-wrapper">
                            <el-input
                                v-model="meetingForm.meetingLocation"
                                placeholder="请输入会议地点"
                                @input="handleLocationSearch"
                                class="location-input"
                            />
                            <div v-show="searchResults.length > 0" class="location-suggestions">
                                <div
                                    v-for="(item, index) in searchResults"
                                    :key="index"
                                    class="suggestion-item"
                                    @click="selectLocation(item)"
                                >
                                    <span class="name">{{ item.name }}</span>
                                    <span class="address">{{ item.address }}</span>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="form-item">
                        <label>具体地点</label>
                        <input v-model="meetingForm.specificLocation" placeholder="请输入具体地点" />
                    </div>
                    <div class="upload-btn-wrapper">
                        <el-upload
                            class="meeting-upload"
                            :action="'/api/admins/uploadCoverImg'"
                            :headers="uploadHeaders"
                            :on-success="handleUploadSuccess"
                            :on-error="handleUploadError"
                            :before-upload="beforeUpload"
                            :limit="4"
                            :on-exceed="handleExceed"
                            :file-list="[]"
                            :show-file-list="false"
                        >
                            <el-button type="danger" :disabled="meetingForm.files.length >= 4">
                                上传会议附件
                            </el-button>
                        </el-upload>
                        <div class="el-upload__tip">最多上传4个附件，每个附件不大于30MB</div>
                    </div>
                </div>

                <!-- 会议附件列表 -->
                <div class="form-item">
                    <div class="file-list-wrapper">
                        <label>会议附件</label>
                        <div v-for="(file, index) in meetingForm.files" :key="index" class="file-item">
                            <div class="file-info">
                                <a 
                                    :href="file.url" 
                                    :download="file.name"
                                    target="_blank"
                                    class="file-name"
                                    @click.stop
                                >
                                    {{ file.name }}
                                </a>
                            </div>
                            <el-icon class="delete-icon" @click.stop="removeFile(index)">
                                <Delete />
                            </el-icon>
                        </div>
                    </div>
                </div>

                <!-- 邀请参会人 -->
                <div class="form-item">
                    <label>邀请参会人</label>
                    <div class="invite-section">
                        <el-input 
                            v-model="searchKeyword" 
                            placeholder="支持搜索姓名、手机号、所属单位、ID" 
                            class="search-input"
                            @keyup.enter="handleSearch"
                        >
                            <template #suffix>
                                <el-icon class="search-icon" @click="handleSearch">
                                    <Search />
                                </el-icon>
                            </template>
                        </el-input>

                        <div class="filter-section">
                            <el-select v-model="filters.identity" placeholder="身份" class="filter-item">
                                <el-option label="身份筛选：全部" value="all" />
                                <el-option label="市级政协委员" value="city" />
                            </el-select>
                            <el-select v-model="filters.region" placeholder="地区" class="filter-item">
                                <el-option label="地区筛选：全部" value="all" />
                            </el-select>
                            <el-select v-model="filters.affiliation" placeholder="界别" class="filter-item">
                                <el-option label="界别筛选：全部" value="all" />
                            </el-select>
                            <el-button 
                                type="danger" 
                                @click="addSelectedParticipants"
                                :disabled="currentSelection.length === 0"
                            >
                                添加所选
                            </el-button>
                        </div>

                        <el-table 
                            ref="participantsTable"
                            :data="participantsList" 
                            @selection-change="handleSelectionChange"
                            class="participants-table"
                            v-loading="loading"
                        >
                            <el-table-column type="selection" width="55" :selectable="(row) => !isParticipantSelected(row)" />
                            <el-table-column prop="uname" label="姓名" />
                            <el-table-column prop="identity" label="身份" />
                            <el-table-column prop="region" label="地区" />
                            <el-table-column prop="affiliation" label="界别" />
                        </el-table>
                    </div>
                </div>

                <!-- 已选参会人列表 -->
                <div class="form-item">
                    <label>参会人名单</label>
                    <div class="selected-participants">
                        <el-table 
                            :data="selectedParticipants"
                            @selection-change="handleSelectedListChange"
                            class="selected-table"
                        >
                            <el-table-column width="55">
                                <template #header>
                                    <span>{{ selectedParticipants.length }}人</span>
                                </template>
                                <template #default="scope">
                                    <el-icon 
                                        :class="['delete-icon', { 'selected': scope.row.isSelected }]"
                                        @click="toggleParticipantSelection(scope.row)"
                                        style="cursor: pointer;"
                                    >
                                        <Delete />
                                    </el-icon>
                                </template>
                            </el-table-column>
                            <el-table-column prop="uname" label="姓名" />
                            <el-table-column prop="identity" label="身份" />
                            <el-table-column prop="region" label="地区" />
                            <el-table-column prop="affiliation" label="界别" />
                            <el-table-column width="120">
                                <template #header>
                                    <el-button 
                                        type="danger" 
                                        size="small" 
                                        @click="removeSelectedParticipants"
                                        :disabled="!hasSelectedToRemove"
                                    >
                                        删除所选
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </div>
            </div>

            <!-- 底部按钮 -->
            <div class="form-actions">
                <el-button type="danger" @click="submitForm">发布</el-button>
            </div>
        </div>


    </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { getParticipants, addMeeting } from '@/api/meetings'
import AMapLoader from '@amap/amap-jsapi-loader'
import { useTokenStore } from '@/stores/token.js'
import { useMeetingsStore } from '@/stores/meetings'
import Time from '@/components/Time.vue'
const meetingsStore = useMeetingsStore()
const router = useRouter()


onMounted(() => {
    fetchParticipants()
    initAMap()
})

const meetingForm = ref({
    title: '',
    description: '',
    organizer: '',
    meetingTime: [],
    meetingLocation: '',
    specificLocation: '',
    files: []
})

const rules = {
    title: [{ required: true, message: '请输入会议题目', trigger: 'blur' }],
    description: [{ required: true, message: '请输入会议简介', trigger: 'blur' }],
    organizer: [{ required: true, message: '请输入主办方', trigger: 'blur' }],
    meetingTime: [{ required: true, message: '请选择会议时间', trigger: 'change' }],
    meetingLocation: [{ required: true, message: '请输入会议地点', trigger: 'blur' }],
    specificLocation: [{ required: true, message: '请输入具体地点', trigger: 'blur' }]
}

const searchKeyword = ref('')
const filters = ref({
    identity: 'all',
    region: 'all',
    affiliation: 'all'
})
const participantsList = ref([])
const selectedParticipants = ref([])
const loading = ref(false)
const currentSelection = ref([]) // 存储当前选中的项
const selectedToRemove = ref([]) // 存储要删除的项
const participantsTable = ref(null)
const dateRange = ref([]) // 会议时间范围

// 地图相关
const searchResults = ref([])
let mapInstance = null
let autoComplete = null

const tokenStore = useTokenStore()

const uploadHeaders = computed(() => ({
  'Authorization': tokenStore.token
}))

// 初始化高德地图
const initAMap = async () => {
    try {
        window._AMapSecurityConfig = {
            securityJsCode: '471c055f43738d0a48758620c81ed465', // 需要替换安全密钥
        }
        
        await AMapLoader.load({
            key: '6b8b624eb7c617e7c16e2eb2941b2081', // 需要替换高德地图 Key
            version: '2.0',
            plugins: ['AMap.AutoComplete']
        })
        
        autoComplete = new AMap.AutoComplete({
            city: '全国'
        })
    } catch (error) {
        console.error('地图初始化失败:', error)
    }
}

// 处理地址搜索
const handleLocationSearch = async (value) => {
    if (!value) {
        searchResults.value = []
        return
    }
    
    try {
        if (!autoComplete) return
        
        autoComplete.search(value, (status, result) => {
            if (status === 'complete' && result.tips) {
                searchResults.value = result.tips.map(tip => ({
                    name: tip.name,
                    address: tip.district + tip.address,
                    location: tip.location,
                    district: tip.district
                }))
            }
        })
    } catch (error) {
        console.error('地址搜索失败:', error)
    }
}

// 选择地址
const selectLocation = (item) => {
    meetingForm.value.meetingLocation = item.name
    meetingForm.value.specificLocation = item.address
    searchResults.value = []
}

// 获取参会人列表
const fetchParticipants = async () => {
    loading.value = true
    try {
        const response = await getParticipants({
            searchText: searchKeyword.value,
            identity: filters.value.identity === 'all' ? '' : filters.value.identity,
            region: filters.value.region === 'all' ? '' : filters.value.region,
            affiliation: filters.value.affiliation === 'all' ? '' : filters.value.affiliation
        })
        if (response.code === 200) {
            participantsList.value = response.data
        } else {
            ElMessage.error(response.msg || '获取参会人列表失败')
        }
    } catch (error) {
        console.error('获取参会人列表错误:', error)
        ElMessage.error('获取参会人列表失败')
    } finally {
        loading.value = false
    }
}

// 搜索参会人
const handleSearch = () => {
    fetchParticipants()
}

// 监听筛选条件变化
watch([() => filters.value.identity, () => filters.value.region, () => filters.value.affiliation], () => {
    fetchParticipants()
})

// 处理选择变化
const handleSelectionChange = (val) => {
    currentSelection.value = val
}

// 添加所选参会人
const addSelectedParticipants = () => {
    if (currentSelection.value.length === 0) {
        return
    }
    
    // 添加新选中的参会人，并确保它们的选中状态为 false
    const newParticipants = currentSelection.value.map(item => ({
        ...item,
        isSelected: false  // 确保新添加的参会人默认未选中
    }))
    
    selectedParticipants.value = [...selectedParticipants.value, ...newParticipants]
    
    // 清空当前选择
    currentSelection.value = []
    
    // 清空表格的选择状态
    if (participantsTable.value) {
        participantsTable.value.clearSelection()
    }
}

// 处理参会人名单的选择变化
const handleSelectedListChange = (val) => {
    selectedToRemove.value = val
}

// 移除选中的参会人
const removeSelectedParticipants = () => {
    if (selectedToRemove.value.length === 0) {
        ElMessage.warning('请先选择要删除的参会人')
        return
    }
    
    // 获取要保留的参会人
    selectedParticipants.value = selectedParticipants.value.filter(item => 
        !selectedToRemove.value.some(selected => selected.uid === item.uid)
    )
    
    // 重置选中状态
    selectedToRemove.value = []
    
    // 清空选中状态
    const selectedTable = document.querySelector('.selected-table')
    if (selectedTable) {
        const headerCheckbox = selectedTable.querySelector('.el-table__header-wrapper .el-checkbox input')
        if (headerCheckbox) {
            headerCheckbox.checked = false
        }
    }

    // 重置邀请列表的选择状态
    if (participantsTable.value) {
        participantsTable.value.clearSelection()
    }
}

// 移除单个参会人
const removeParticipant = (index) => {
    const removedParticipant = selectedParticipants.value[index]
    selectedParticipants.value.splice(index, 1)
    
    // 重置邀请列表中该参会人的选择状态
    if (participantsTable.value) {
        participantsTable.value.clearSelection()
    }
}

// 判断参会人是否已被选中
const isParticipantSelected = (participant) => {
    return selectedParticipants.value.some(p => p.uid === participant.uid)
}

// 处理单个选择变化
const handleSingleSelect = (val, participant) => {
    if (val) {
        if (!currentSelection.value.some(p => p.uid === participant.uid)) {
            currentSelection.value.push(participant)
        }
    } else {
        currentSelection.value = currentSelection.value.filter(p => p.uid !== participant.uid)
    }
}

// 处理参会人选择状态切换
const toggleParticipantSelection = (participant) => {
    participant.isSelected = !participant.isSelected
    if (participant.isSelected) {
        if (!selectedToRemove.value.some(p => p.uid === participant.uid)) {
            selectedToRemove.value.push(participant)
        }
    } else {
        selectedToRemove.value = selectedToRemove.value.filter(p => p.uid !== participant.uid)
    }
}

const hasSelectedToRemove = computed(() => {
    return selectedToRemove.value.length > 0
})

const handleBack = () => {
    ElMessageBox.confirm('确定要离开吗？未保存的内容将会丢失', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        router.back()
    }).catch(() => {})
}

// 处理文件超出限制
const handleExceed = () => {
  ElMessage.warning('最多只能上传4个附件')
}

// 上传前的验证
const beforeUpload = (file) => {
  // 验证文件大小
  const isLt30M = file.size / 1024 / 1024 < 30
  if (!isLt30M) {
    ElMessage.error('文件大小不能超过 30MB!')
    return false
  }
  
  // 验证文件数量
  if (meetingForm.value.files.length >= 4) {
    ElMessage.error('最多只能上传4个附件!')
    return false
  }
  return true
}

// 上传成功的回调
const handleUploadSuccess = (response, file) => {
  if (response.code === 200) {
    meetingForm.value.files.push({
      name: file.name,
      url: response.data
    })
    ElMessage.success('上传成功')
  } else {
    ElMessage.error(response.msg || '上传失败')
  }
}

// 上传失败的回调
const handleUploadError = (error) => {
  console.error('上传错误:', error)
  ElMessage.error('文件上传失败')
}

// 移除文件
const removeFile = (index) => {
  ElMessageBox.confirm('确定要删除这个附件吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    meetingForm.value.files.splice(index, 1)
    ElMessage.success('删除成功')
  }).catch(() => {})
}

const submitForm = async () => {
    // 验证表单
    if (!meetingForm.value.title) {
        ElMessage.error('请输入会议题目')
        return
    }
    if (!meetingForm.value.description) {
        ElMessage.error('请输入会议简介')
        return
    }
    if (!meetingForm.value.organizer) {
        ElMessage.error('请输入主办方')
        return
    }
    if (!dateRange.value[0] || !dateRange.value[1]) {
        ElMessage.error('请选择会议签到时间')
        return
    }
    if (!meetingForm.value.meetingLocation) {
        ElMessage.error('请输入会议地点')
        return
    }
    if (!meetingForm.value.specificLocation) {
        ElMessage.error('请输入具体地点')
        return
    }
    if (selectedParticipants.value.length === 0) {
        ElMessage.error('请至少选择一位参会人')
        return
    }

    try {
        // 组织会议数据
        const meetingData = {
            title: meetingForm.value.title,
            introduction: meetingForm.value.description,
            organizer: meetingForm.value.organizer,
            startTime: dateRange.value[0].substring(0, 16),  // 只取到分钟
            endTime: dateRange.value[1].substring(0, 16),    // 只取到分钟
            location1: meetingForm.value.meetingLocation,
            location2: meetingForm.value.specificLocation,
            files: meetingForm.value.files,
            participantIds: selectedParticipants.value.map(p => p.uid)
        }

        // 显示加载中
        loading.value = true

        // 发送请求
        const response = await addMeeting(meetingData)
        
        if (response.code === 200) {
            ElMessage.success('会议发布成功')
            // 发布成功后返回会议列表页面
            meetingsStore.fetchMeetings()
            router.push({ name: 'MeetingList' })
        } else {
            ElMessage.error(response.msg || '发布失败')
        }
    } catch (error) {
        console.error('发布会议失败:', error)
        ElMessage.error('发布失败：' + (error.message || '未知错误'))
    } finally {
        loading.value = false
    }
}
</script>

<style scoped>
@import '@/assets/css/header/index.css';
@import '@/assets/css/meeting/addMeeting.css';

</style>
